import {
  api,
  util,
  storage,
  dialog,
  forms,
  clickIncrement,
  clearIncrement,
  getSign
} from '../../../js/util';
import {
  router
} from '../../../js/router';
import {
  cart,
  order
} from '../../../js/modules/order';
import {
  list,
  detail,
  mall,
  scant
} from '../../../js/modules/mall';
import { 
  activities
} from '../../../js/modules/market';
import {
  GoodsNumCache
} from '../../../js/modules/propertycache.js'
import {
  address
} from '../../../js/modules/store';
import {
  theme
} from '../../../js/modules/theme';
import authorize from '../../../js/modules/authorize';
const info = require("../../../js/modules/info.js");
import {
  category
} from "../../../js/modules/gloab";
const app = getApp()
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  lifetimes: {
    attached() {
    
      this.filterComponent = this.selectComponent("#filterComponent")
      // 在组件实例进入页面节点树时执行
      this.fasterComponent = this.selectComponent("#fasterComponent");
      this.outofstock = this.selectComponent("#outofstock");
      this.deliveryComponent = this.selectComponent("#deliveryComponent");
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的属性列表
   */
  properties: {
    hasNav: {
      value: false,
      type: Boolean
    },
    hasMaket: {
      value: false,
      type: Boolean
    },
    marketSource: {
      value: {},
      type: Object
    },
    inFast: {
      value: false,
      type: Boolean
    },
    showSwitch:{
      value:false,
      type:Boolean
    },
    showStyle:{
      value:"line",
      type:String
    },
    isScanty: {
      value:false,
      type:Boolean,
      observer(newVal) {
        if (!this.data.enableZeroStockBuy&&this.data.isScanty){
          this.setData({
            isShowZeroStock:1
          })
        }
        else if (!this.data.enableZeroStockBuy && !this.data.isScanty){
          this.setData({
            isShowZeroStock: 0
          })
        }

      }
    },
    enableZeroStockBuy: {
      value: false,
      type: Boolean
    },
    quantityDigits: {
      value: 0,
      type: Number
    },
    priceDigits:{
      value: 2,
      type: Number
    },
    decimalDigits: {
      value: 2,
      type: Number
    },
    showRetailPrice:{
      value:false,
      type:Boolean
    },
    spectStyle:{
      value:0,
      type:Number
    },
    addressAssignDepot:{
      value:false,
      type:Boolean
    },
    goods:{
      value:false,
      type:Array
    },
    Currency:{
      value:false,
      type:String
    },
    NotShowProductNoneOffered: { // 不显示无货商品
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    PageIndex: 1,
    PageSize: 20,
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    mainColor: api.titleColor||"#e56b14",//主题色
    sortField: "sortorder",
    sortDirect: "desc",
    bid: "",//品牌
    cid: 0,//分类
    typeId: 0,//类型
    rule_id: 0, //优惠券规则id
    tag_id:0,//标签id
    isShowZeroStock: 0,//是否显示零库存
    keywords: "",
    showStyle: 'line',
    hasMoreData: true,
    isLoadComplete: false,
    goodsList: [],
    nowGoodsId: 0,
    scantyProduct: [],
    priceRange: [],
    is_search: false,
    tree: null,
    time:null,
    isLogin:false,
    showFilter: false, //是否显示筛选
    cacheData:{},
    proprietorId:0,
    extattrs:"",
    minprice:"",
    addr:{area:"",code:""},
    thumb:200
  },
  behaviors: [componentBehavior],
  /**
   * 组件的方法列表
   */
  methods: {
    /**获得签名 */
    getSiginData() {
      let param = this.get_param();
      delete param.PageIndex;
      return getSign(param);
    },
    //确定
    bindDefine:function(){
      var list = this.data.goodsList;
      var array = [];
      for(var i = 0;i<list.length;i++){
        if(list[i].isSelected){
          array.push({SaleValue:list[i].ProductId,image:list[i].DefaultPicUrl})
        }
      }
      if(array.length == 0){
        util.alert('请选择商品');
        return;
      }else if(array.length > 30){
        util.alert('最多只能选择30个商品，请重新选择');
        return;
      }
      this.triggerEvent('addGoods',array);
    },
    /**
     * 加载入口
     * 
     */
    loadMain() {
      var that = this;
      //判断是否登录
      if (app.dns.proprietorId == 0 && !authorize.isLogin('store')) {
        authorize.redirect('store');
        return;
      }
      //是否处于搜索模式
      if (that.data.is_search) {
        that.data.is_search = false;
        //如果条件没有发生变化不进行加载
        var sigin = this.getSiginData();
        if (sigin == that.data.sigin) {
          if (that.data.time&&GoodsNumCache.compareTime(that.data.time))          {
            var goodsList = that.data.goodsList;
            for (var i = 0; i < goodsList.length;i++){
              goodsList[i].CartCount = GoodsNumCache.getProductNum(goodsList[i].ProductId, goodsList[i].CartCount,goodsList[i].IsSingle==1);
             
            }
            that.setData({
              goodsList: goodsList,
              isLogin: authorize.isLogin('store')
            });
          }
          
          //重新加载标签
          // that.loadProductActivities(that, that.data.goodsList, 0);
          return;
          }
      }
      that.setData({
        PageIndex: 1,
        keywords: that.data.keywords,
        isLogin: authorize.isLogin('store')
      });
      if (this.data.addressAssignDepot){
        this.deliveryComponent.getDefaultAddress();
      }
      else{
        this.selectedAdress({detail:{Area:"",Code:""}})
      }

      this.loadFirstCategory();
    },
    /**
 * 加载类别 
 * */
    loadFirstCategory() {
      let entity = authorize.getEntity();
      let fkId = 0;
      if (entity) {
        fkId = entity.fkId;
      }
      this.data.fkId = fkId;
      if (this.data.tabKey != "category_" + app.dns.proprietorId + "_" + fkId) {
        this.data.tabKey = "category_" + app.dns.proprietorId + "_" + fkId;
      }
      else{
        return;
      }
      var that = this;
      list.loadCategories(0, (content)=> {
        this.initCategory(content)
      });
    },
    filterCategory(firstCatgeory,allCateogry){
      if (firstCatgeory.length == allCateogry.length) return allCateogry;
      let categoryIds=[];
      firstCatgeory.map((item)=>{
        categoryIds.push(item.Id);
      });
      allCateogry= allCateogry.filter((item) => categoryIds.indexOf(item.Id)>-1);
      return allCateogry;
    },
    /**
    * 加载目录信息 
    * */
    loadCategoryinfo(callback) {
      var that = this;
      let { cid}=this.data;
      list.loadCategoryinfo(cid, (content) => {
        this.setData({
          priceRange: content.PriceRange||[]
        })
      });
      if (cid == 0) {
        callback(); 
        return;
      }
      //取缓存中的分类数据
      // category.load(app.dns.proprietorId, app.dns.proprietor, 0, (res) => {
      //   let tree = res.Content;
      //   let obj=tree.filter((item) => item.Id == cid);
      //   this.setData({
      //     priceRange: obj&&obj.length>0?obj[0].PriceRange:[]
      //   });
      //   callback();
      // });
    },
    /**
     * 初始化分类
     */
    initCategory(firstCatgeory) {
      let that = this;
      let { selectedCategoryId}=this.data;
      category.load(app.dns.proprietorId, app.dns.proprietor, 0, (res) => {
        let tree = that.filterCategory(firstCatgeory,res.Content);
        //分类
        let layer = 0;
        that.data.tree=tree;
        let obj = that.get_node_by_cid(that, selectedCategoryId);
        if (obj != null) {
          layer = obj.layer;
          that.data.typeId = obj.category.TypeId;
        }
        if (selectedCategoryId != 0 && layer != 3) {
          //设置节点是否展开
          that.set_current_node_isopen(that, layer, selectedCategoryId);
        }
        //设置父级节点选中状态
        that.set_node_parent_selected(that, selectedCategoryId);

        that.setData({
          cid: that.data.cid,
          tree: that.data.tree
        });
        if (that.filterComponent != null) {
          that.filterComponent.setData({
            typeId: that.data.typeId,
            bid: that.data.bid
          });
        }
      },true);
    

    },

    /**
     * 获得要请求的参数
     */
    get_param() {
      let { PageIndex, PageSize, keywords, sortField,sortDirect, cid, bid, rule_id, tag_id, minprice, extattrs, enableZeroStockBuy, isShowZeroStock,addr}=this.data;
      return {
        PageIndex: PageIndex,
        PageSize: PageSize,
        keywords: keywords,
        sortField: sortField,
        sortDirect: sortDirect,
        cid: cid,
        bid: bid,
        rule_id: rule_id,
        tag_id: tag_id,
        minprice: minprice,
        extattrs: extattrs,
        isShowZeroStock: enableZeroStockBuy?1:isShowZeroStock,
        areaCode:addr.code
      };
    },
    /**加载商品列表 */
    loadProductList(callback) {
      var that = this;
      let param=that.get_param();
      //设置签名（如果签名相同，则不进行加载）
      that.data.sigin = that.getSiginData();
      list.loadProductList(param,function (res, isCache) {

        var contentlistTem = that.data.goodsList;
        if (that.data.PageIndex == 1) {
          contentlistTem = [];
        }
        if (res.Content.TotalCount > 0) {
          var contentlist = res.Content.Data;
          var totalPage = res.Content.TotalPage;
          var hasMoreData = res.Content.TotalCount > (that.data.PageIndex) * that.data.PageSize;
          var index = contentlistTem.length;
          var goodlist = contentlistTem.concat(contentlist);
          
          var good = that.data.goods;
          if(good.length > 0){
            for(var i=0;i<goodlist.length;i++){
              for(var j=0;j<good.length;j++){
                if(goodlist[i].ProductId == good[j].SaleValue){
                  goodlist[i].isSelected = true;
                }
              }
            }
          }
          // console.log(goodlist,'--===',that.data.goods);
          //先填充页面
          that.setData({
            goodsList: goodlist,
            hasMoreData: hasMoreData,
            isLoadComplete: true,
            time:new Date().getTime()
          });
 
          if (!isCache){
            if (callback && typeof (callback) == "function") {
              callback(goodlist, that.data.PageIndex);
            }
            // that.loadProductActivities(that, contentlist, index);
          }
        } else {
          that.setData({
            goodsList: [],
            hasMoreData: true,
            isLoadComplete:true,
            PageIndex: 1
          },()=>{
            if (callback && typeof (callback) == "function") {
              callback([], that.data.PageIndex);
            }
          });
        }
      });
    },
    loadProductActivities(that,contentlist,index){
      //加载促销信息
      activities.loadProductActivities(contentlist, this.data.hasMaket, 0, this.data.addr.code, function (source, index) {
        var len = that.data.goodsList.length;
        for (var i = 0; i < source.length && index + i < len; i++) {
          that.data.goodsList[index + i] = source[i];
        }
        // item.isSelected = false
        let obj = that.data.goodsList;
        obj.map(function(item,index){
          item.market = Array.from(new Set(item.market))
          item.isSelected = false
        })
        // obj.map((item)=>item.market = Array.from(new Set(item.market)));    //营销标识去重
        //重新渲染
        that.setData({
          goodsList: obj,
        });
        console.log(that.data.goodsList,'----1');
      }, index);
    },
    /**搜索 */
    bindSearch(e) {
      var that = this;
      clickIncrement(()=> {
        this.setData({
          bid: "",
          cid: 0,
          extattrs: "",
          minprice: "",
         priceRange : [],
          typeId : 0
        })
        that.data.keywords = e.detail;
        that.data.PageIndex = 1;
        that.loadProductList();
      });

    },

    /*
    弹出缺货登记的层 
    */
    showScantyModal(e) {
      var that = this;
      var idx = e.currentTarget.dataset.idx;
      var product = that.data.goodsList[idx];
      if (product.IsSingle == 0) {
        that.onShowGoodsModal({ detail: { product: product, idx: idx } });
      } else {
        that.outofstock.setData({
          scantyProduct: product,
        })
        that.outofstock.openScanyDialog(e);
      }
    },
   
    /**判断是否登录 */
    isLogin() {
      if (!authorize.isLogin('store')) {
        authorize.redirect('store');
        return;
      }
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
      wx.stopPullDownRefresh();
      this.data.PageIndex = 1;
      this.loadProductList();
      this.data.tabKey="";
      this.loadFirstCategory();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
      if (this.data.hasMoreData) {
        this.data.PageIndex += 1;
        let { cacheData}=this.data;
        let sigin = this.getSiginData();
        this.loadProductList((list, page_index) => {
          if (!cacheData[sigin])return;
          cacheData[sigin].list=list;
          cacheData[sigin].page_index=page_index;
          this.data.cacheData = cacheData;
        });
      }
    },
    /**
     * 选择目录
     *  */
    selectedCategory(e,categoryid,level) {
      var that = this;
      var selectedCategoryId,layer;
      var o = e.currentTarget.dataset;
      selectedCategoryId = o.categoryid;
      layer = o.level;

      clickIncrement(()=> {
        let isShowZeroStock = 0;
        let { cid, isScanty, enableZeroStockBuy } = this.data;
        if (!enableZeroStockBuy && isScanty) {
          isShowZeroStock = 1;
        }

        if (layer != 3) {
          //设置节点是否展开
          that.set_current_node_isopen(that, layer, selectedCategoryId);
        }
        //设置父级节点选中状态
        that.set_node_parent_selected(that, selectedCategoryId);
        if (cid == selectedCategoryId){
          that.setData({
            tree: that.data.tree
          });
          return;
        }
        else{
          that.setData({
            bid: "",
            extattrs: "",
            isShowZeroStock: isShowZeroStock,
            minprice: "",
            cid: selectedCategoryId,
            tree: that.data.tree
          });
        }     

        //设置当前的价格区间
        var obj = that.get_node_by_cid(that, selectedCategoryId);

        var priceRange = obj == null ? [] : (obj.category.PriceRange || []);
        if (obj != null) {
          that.data.priceRange = priceRange;
          that.data.typeId = obj.category.TypeId;
        } 
        else{
          that.data.priceRange = [];
          that.data.typeId = 0;
        }
        // that.filterComponent.setData({
        //   cid: selectedCategoryId,
        //   typeId: that.data.typeId,
        //   priceRange: that.data.priceRange,
        // })

        let sigin = that.getSiginData();

        if (that.isCacheCategory(sigin)) return;
        //重新加载页面
        that.data.PageIndex = 1;
        
        let cacheData = that.data.cacheData;
        that.loadProductList((list,page_index)=>{
          cacheData[sigin]={
            list : list,
            time : new Date().getTime(),
            scrollTop : 0,
            page_index:page_index
          }
          this.triggerEvent("onPageScrollTo", {
            scrollTop: 0
          });  
          that.data.cacheData = cacheData;
        });
      });

    },
    /**
     * 是否有分类缓存
     */
    isCacheCategory(sigin){
      let { cacheData}=this.data;
      let that=this;

      let keys = Object.keys(cacheData);
      if (keys.length>0&&keys.indexOf(sigin)>-1) {
        let obj = cacheData[sigin];
        let list = cacheData[sigin].list;
        var goodsList = list;
        if (list.length > 0 && GoodsNumCache.compareTime(obj.time)){         
          for (var i = 0; i < goodsList.length; i++) {
            goodsList[i].CartCount = GoodsNumCache.getProductNum(goodsList[i].ProductId, goodsList[i].CartCount,goodsList[i].IsSingle==1);
          }
   
        }
        that.data.sigin = sigin;
        that.data.PageIndex = obj.page_index;
        that.setData({
          goodsList: goodsList
        });
        this.triggerEvent("onPageScrollTo", {
          scrollTop: obj.scrollTop
        });
        return true;
      }
    },
    /**
     * 设置滚动位置
     */
    setScollTop(scrollTop){
      let { cacheData}=this.data;
      let sigin = this.getSiginData();
      let keys = Object.keys(cacheData);
      if (keys.length > 0 && keys.indexOf(sigin) > -1) {
        let obj = cacheData[sigin];
        obj.scrollTop = scrollTop;
      }
    },
    /**
     * 设置节点是否展开
     */
    set_current_node_isopen(that, layer, selectedCategoryId) {
      for (var i in that.data.tree) {
        var first = that.data.tree[i];
        //父级是否选中
        first.parentselected = false;
        if (selectedCategoryId == first.Id) {
          first.isopen = !first.isopen;
        } else if (layer == 1 || layer == 0) {
          first.isopen = false;
        }
        for (var j in first.Children) {
          var second = first.Children[j];
          second.parentselected = false;
          if (selectedCategoryId == second.Id) {
            second.isopen = !second.isopen;
            first.parentselected = true;
          } else if (layer == 2 || layer == 0) {
            second.isopen = false;
          }
        }
      }
    },
    /**
     * 设置父级节点选中状态
     */
    set_node_parent_selected(that, selectedCategoryId) {
      for (var i in that.data.tree) {
        var first = that.data.tree[i];
        if (selectedCategoryId == first.Id) {
          break;
        }
        for (var j in first.Children) {
          var second = first.Children[j];
          if (selectedCategoryId == second.Id) {
            first.parentselected = true;
            break;
          }
          for (var k in second.Children) {
            if (selectedCategoryId == second.Children[k].Id) {
              second.parentselected = true;
              break;
            }
          }
        }
      }
    },
    /**
     * 获得节点
     *  */
    get_node_by_cid(that, selectedCategoryId) {
      for (var i in that.data.tree) {
        var first = that.data.tree[i];
        if (selectedCategoryId == first.Id) {
          return {
            category: first,
            layer: 1
          };
        }
        for (var j in first.Children) {
          var second = first.Children[j];
          if (selectedCategoryId == second.Id) {
            return {
              category: second,
              layer: 2
            };
          }
          for (var k in second.Children) {
            if (selectedCategoryId == second.Children[k].Id) {
              return {
                category: second.Children[k],
                layer: 3
              };
            }
          }
        }
      }
      return null;
    },
    onImageLoadError() {
      var that = this;
      that.setData({
        pic: "/assets/images/img.png"
      })
    },
    /**显示多规则 */
    onShowGoodsModal(e) {
      var that = this;
      e = e.detail;
      let { addr, priceDigits, decimalDigits, quantityDigits, isScanty, hasMaket } = this.data;
      that.fasterComponent.setData({
        item: e.product,
        isScanty: isScanty,
        quantityDigits: quantityDigits,
        priceDigits: priceDigits,
        decimalDigits: decimalDigits,
        areaCode: addr.code,
        hasMaket: hasMaket,
        addCompleted: function (goods) {
          console.log(goods,'-----商品');
          that.onAddCartCompleted({ detail: { product: goods, idx: e.idx} });
        }
      });
      that.fasterComponent.onShowGoodsModal(e);
    },
    /**
     * 加入完成后调用，更新界面显示数量
     */
    onAddCartCompleted(e) {
      e = e.detail;
      let key = "goodsList[" + e.idx + "]";
      this.setData({
        [key]: e.product
      });
    },
    toDetail(e){
      var index = e.currentTarget.dataset.index;
      var item = this.data.goodsList[index];
      item.isSelected = !item.isSelected;
      this.setData({
        goodsList: this.data.goodsList
      });
      // console.log(goodsList,'----id');
    },
    
    // toDetail(e) {
    //   var pagetype = e.currentTarget.dataset.pagetype;
    //   var linkparam = e.currentTarget.dataset.linkparam;
    //   var loadcomplate = e.currentTarget.dataset.loadcomplate;
    //   if (this.data.hasMaket) {
    //     pagetype=0;
    //     linkparam = "productId=" + e.currentTarget.dataset.id + "&id=" + e.currentTarget.dataset.id
    //   }
    //   if (loadcomplate != 1) return;
    //   var url = "productDetail";
    //   if (pagetype == 1 || pagetype == 2) {
    //     url = "groupDetail";
    //   }
    //   theme.routerTo(url, linkparam);

    // },
    showDelivery(e){
      this.deliveryComponent.loadAdressList(e);
    },
    /**
     * 配送至弹层选择地址
     */
    selectedAdress(e){
      let that=this;
      this.data.PageIndex = 1;

      this.setData({
        addr: { area: e.detail.Area, code: e.detail.Code}
      },()=>{
        let { cacheData}=that.data;
        let sigin = that.getSiginData();
        this.loadProductList((list,page_index)=>{
           cacheData[sigin] = {
             list: list,
             time: new Date().getTime(),
             scrollTop: 0,
             page_index:page_index
           }
           that.data.cacheData = cacheData;
           that.completeCallBack();
         });
      })
    },
    onUnload(){
      clearTimer();
    },
    completeCallBack() {
      let { proprietorId}=this.data;
       if (proprietorId != app.dns.proprietorId){
         proprietorId = app.dns.proprietorId;
         this.loadCategoryinfo(()=>{
          //  this.filterComponent.get_category_screens();
         });

      }
      this.data.proprietorId = proprietorId;
    },
    /**
   * 切换样式
   */
    switchView() {
      let { showStyle}=this.data;
      this.setData({
        showStyle: showStyle=='line'?'view':'line',
        thumb: showStyle == 'line' ? 300 : 200
      })
    },
   
  }
})